package com.example.springdemo.datasource;

import com.zaxxer.hikari.HikariDataSource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;

/**
 * 多数据源配置
 *
 * @author wanghuajun
 * @version 1.0
 * @date 2019-08-09 22:15
 */
@Slf4j
@Data
@ConfigurationProperties(prefix = "content-center.datasource")
public class MultipleDataSourceProperties {

    private String url;

    private String username;

    private String password;

    private String driverClassName;

    public void config(HikariDataSource hikariDataSource){
        log.info("开始设置MultipleDataSourceProperties#config数据源信息！");

        hikariDataSource.setJdbcUrl(url);
        hikariDataSource.setUsername(username);
        hikariDataSource.setPassword(password);

        hikariDataSource.setDriverClassName(StringUtils.isEmpty(driverClassName) ? "com.mysql.cj.jdbc.Driver" : driverClassName);

        hikariDataSource.addDataSourceProperty("cachePrepStmts", "true"); //是否自定义配置，为true时下面两个参数才生效
        hikariDataSource.addDataSourceProperty("prepStmtCacheSize", "250"); //连接池大小默认25，官方推荐250-500
        hikariDataSource.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); //单条语句最大长度默认256，官方推荐2048
        hikariDataSource.addDataSourceProperty("useServerPrepStmts", "true"); //新版本MySQL支持服务器端准备，开启能够得到显著性能提升
        hikariDataSource.addDataSourceProperty("useLocalSessionState", "true");
        hikariDataSource.addDataSourceProperty("useLocalTransactionState", "true");
        hikariDataSource.addDataSourceProperty("rewriteBatchedStatements", "true");
        hikariDataSource.addDataSourceProperty("cacheResultSetMetadata", "true");
        hikariDataSource.addDataSourceProperty("cacheServerConfiguration", "true");
        hikariDataSource.addDataSourceProperty("elideSetAutoCommits", "true");
        hikariDataSource.addDataSourceProperty("maintainTimeStats", "false");
    }
}
